/**
 * Created by bearzhao on 14-10-23.
 */
/*表单对象*/
; (function ($, window, undefined) {
    "use strict";
    //#region btn
    var btn = function ($btn, obj) {
        var self = this;
        self.form = obj.form;
        self.$btn = $btn;
        var type = $btn.attr("type");
        self.$btn.bind("click.form", function () {
            var v = 0;
            for (var i = 0, max = obj.$element.size() ; i < max; i++) {
                if (obj.$element.eq(i).data("result") === undefined) {
                    obj.$element.eq(i).input().doVerification();
                }
                obj.$element.eq(i).data("result") && !obj.$element.eq(i).data("result").result && v++;
            }
            v <= 0 && self[$btn.attr("type")]();
        });

    };
    btn.prototype.submit = function () {
        var self = this;
        self.form.submit();
    };
    btn.prototype.other = function () {
    };
    btn.prototype.close = function () {
        //$("jwindow#" + this.$btn.attr("lid"), window.top.document).find("iframe").jWindow("close");
    };
    btn.prototype.cancel = function () {
        var url = GetQueryString("r");
        if (url) {
            window.location.href = url;
        }
        else {
            window.history.back();
        }
    };
    btn.prototype.button = function () {
        window.ButtonClick();
    };
    //#endregion

    //#region 表单对象
    var form = function (form) {
        this.btns = [];
        this.form = form;
        this.$element = form.find("input,textarea[name],select").map(function () {
            var $this = $(this);
            var t = $this.attr("type");
            if ($.inArray(t, ["button", "submit", "reset"]) == -1) {
                return $this;
            }
        }).map(function () {
            return $(this)[0];
        });
        for (var i = 0, max = this.$element.size() ; i < max; i++) {
            this.$element.eq(i).input();
        }
        var $btn = form.find("a[tag=button]");
        for (var i = 0, max = $btn.size() ; i < max; i++) {
            this.btns.push(new btn($btn.eq(i), this));
        }
    };
    //#endregion

    $(function () {
        var $form = $("form");
        window.forms = [];
        for (var i = 0, max = $form.size() ; i < max; i++) {
            var $this = $form.eq(i);
            if ($this.attr("mark") !== "StockForm") {
                //throw new Error("创建表单出错");
                return false;
            }
            window.forms.push(new form($this));
        }
    });
}(window.jQuery, window));

